package com.sxt.practiceapplication.activities.course;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.common.base.Strings;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.cache.CacheMode;
import com.lzy.okhttputils.callback.StringCallback;
import com.shuyu.gsyvideoplayer.GSYBaseActivityDetail;
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder;
import com.sxt.practiceapplication.R;
import com.sxt.practiceapplication.common.Urls;
import com.sxt.practiceapplication.entity.baseentity.Data;
import com.sxt.practiceapplication.entity.course.CourseItem;
import com.sxt.practiceapplication.entity.course.CourseVideoItem;
import com.sxt.practiceapplication.entity.course.data.CourseVideoListData;
import com.sxt.practiceapplication.entity.studyrecord.data.StudyRecordAddParam;
import com.sxt.practiceapplication.entity.user.LoginData;
import com.sxt.practiceapplication.utils.GsonBinder;
import com.sxt.practiceapplication.utils.LoginUser;
import com.sxt.practiceapplication.utils.ToastUtils;
import com.sxt.practiceapplication.utils.floatutil.FloatWindow;
import com.sxt.practiceapplication.utils.floatutil.IFloatWindow;
import com.sxt.practiceapplication.utils.floatutil.Util;
import com.sxt.practiceapplication.databinding.ActivityCourseBinding;

import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

public class CourseActivity extends GSYBaseActivityDetail<CourseSampleControlVideo> {

    private String videoUrl = "https://gumengsxt.oss-cn-hangzhou.aliyuncs.com/test/123.mov";

    private CourseSampleControlVideo videoPlayer;

    private CourseItem course;
    private ActivityCourseBinding courseBinding;
    private TextView noVideoTip;
    private String videoTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 使页面沉浸
        setStatusBar();

        // 初始化根视图
        initView();

        // 初始化视图数据
        initContentViewData();

        getCourseVideo();

        videoPlayer.setOnShotClickListener(this::shotImage);

    }

    private void initView() {
        courseBinding = ActivityCourseBinding.inflate(getLayoutInflater());
        setContentView(courseBinding.getRoot());
        if (!Util.hasAlertWindowPermission(this)) {
            requestAlertWindowPermission();
        }
        videoPlayer = courseBinding.videoPlayer;
        noVideoTip = courseBinding.noVideoTip;
    }

    private void getCourseVideo() {
        OkHttpUtils.get(Urls.COURSE_VIDEO_URL + "?course=" + course.getId())
                .tag(this)
                .cacheMode(CacheMode.NO_CACHE)
                .headers("Authorization", LoginUser.getCurrentUserData(this).getToken())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String result, Call call, Response response) {
                        CourseVideoListData courseVideoListData = GsonBinder.toObj(result, CourseVideoListData.class);
                        if (courseVideoListData != null) {
                            Data<List<CourseVideoItem>> videoListData = courseVideoListData.getData();
                            if (videoListData != null) {
                                List<CourseVideoItem> videoItems = videoListData.getResults();
                                if (!videoItems.isEmpty()) {
                                    CourseVideoItem videoItem = videoItems.get(0);
                                    String videoLink = videoItem.getVideoLink();
                                    if (!Strings.isNullOrEmpty(videoLink)) {
                                        videoUrl = videoLink;
                                        videoTitle = videoItem.getVideoTitle();
                                        initVideoBuilderMode();
                                        return;
                                    }
                                }
                            }
                        }
                        noVideoTip.setVisibility(View.VISIBLE);
                    }
                });


    }

    private void initContentViewData() {
        course = (CourseItem) getIntent().getSerializableExtra("course");

        videoPlayer.getTitleTextView().setVisibility(View.GONE);
        videoPlayer.getBackButton().setOnClickListener(v -> finish());

        courseBinding.tvCourseTitle.setText(course.getCourseTittle());
        CourseItem.CourseType type = course.getType();
        courseBinding.tvCourseType.setText(type != null ? type.getType() : "未知类型");
        CourseItem.Teacher teacher = course.getTeacher();
        courseBinding.tvTeacherNickname.setText(teacher != null ? teacher.getNickname() : "未知教师");
        courseBinding.tvCourseDes.setText(course.getCourseDes());
        courseBinding.tvCreateTime.setText(course.getCreatedTime());

        addStudyRecord(course);
    }

    private void addStudyRecord(CourseItem course) {
        if (isLogin()) {
            LoginData userData = LoginUser.getCurrentUserData(this);
            OkHttpUtils.post(Urls.ADD_STUDY_RECORD_URL)
                    .tag(this)
                    .cacheMode(CacheMode.NO_CACHE)
                    .headers("Authorization", userData.getToken())
                    .upJson(GsonBinder.toJsonStr(new StudyRecordAddParam(course.getId())))
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {

                        }
                    });
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        IFloatWindow floatWindow = FloatWindow.get();
        if (floatWindow != null) {
            floatWindow.show();
        }
//        showFull();
        videoPlayer.cameraUtil.initSurfaceTexture();
//        detailPlayer.cameraUtil.setPreviewCallback((mImageReader, handler) -> mImageReader.setOnImageAvailableListener(reader -> {
//            Image image = reader.acquireLatestImage();
//            if (image != null) {
//                handler.post(new ImageSaver(image, this));
//            }
//        }, handler));
    }

    /**
     * 是否启动旋转横屏，true表示启动
     *
     * @return true
     */
    @Override
    public boolean getDetailOrientationRotateAuto() {
        return true;
    }


    /**
     * 选择builder模式
     */
    public void initVideoBuilderMode() {
        initVideo();
        getGSYVideoOptionBuilder().
                setVideoAllCallBack(this)
                .build(getGSYVideoPlayer());
    }

    @Override
    public CourseSampleControlVideo getGSYVideoPlayer() {
        return videoPlayer;
    }

    @Override
    public GSYVideoOptionBuilder getGSYVideoOptionBuilder() {
        //内置封面可参考SampleCoverVideo
        ImageView imageView = new ImageView(this);
        loadCover(imageView, videoUrl);
        return new GSYVideoOptionBuilder()
                .setThumbImageView(imageView)
                .setUrl(videoUrl)
                .setCacheWithPlay(true)
                .setVideoTitle(videoTitle)
                .setIsTouchWiget(true)
                .setRotateViewAuto(false)
                .setLockLand(false)
                .setShowFullAnimation(false)
                .setNeedLockFull(true)
                .setSeekRatio(1);
    }

    private void loadCover(ImageView imageView, String url) {

        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setImageResource(R.mipmap.xxx1);

        Glide.with(this.getApplicationContext())
                .setDefaultRequestOptions(
                        new RequestOptions()
                                .frame(3000000)
                                .centerCrop()
                                .error(R.mipmap.xxx2)
                                .placeholder(R.mipmap.xxx1))
                .load(url)
                .into(imageView);
    }

    @Override
    public void clickForFullScreen() {

    }


    /**
     * 视频截图
     * 这里没有做读写本地sd卡的权限处理
     */
    private void shotImage(final View v) {
        // 借用截图按钮来测试拍照
        videoPlayer.cameraUtil.switchCameraFacing();
    }

    @Override
    protected void onPause() {
        super.onPause();

        IFloatWindow floatWindow = FloatWindow.get();
        if (floatWindow != null) {
            floatWindow.hide();
        }

        if (videoPlayer.cameraUtil.isCameraStarted()) {
            videoPlayer.cameraUtil.closeCamera();
        }

        videoPlayer.gestureCompareService.stopGestureComparing();
    }

    @SuppressWarnings("deprecation")
    public void requestAlertWindowPermission() {
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
        startActivityForResult(intent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //todo 用23以上编译即可出现canDrawOverlays
        if (!Util.hasAlertWindowPermission(this)) {
            ToastUtils.show("缺少应用运行的必须权限");
            this.finish();
        }
    }

    /**
     * 沉浸式实现
     */
    protected void setStatusBar() {
        Window window = getWindow();
        View decorView = window.getDecorView();
        int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
        decorView.setSystemUiVisibility(option);
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(Color.TRANSPARENT);
    }

    private boolean isLogin() {
        return LoginUser.isLogin(this);
    }

}